from flask import Blueprint, request
from sqlalchemy import desc,func
import jwt
from collections import Counter

from entity.Response import success,error
from entity.Question import Question
from entity.User import User
from entity.Answer import Answer
from entity.Message import Message
from controller.LoginController import jwt_secret_key
from db import db

questionController = Blueprint('questionController',__name__)

"""
在线提问
input:
问题内容
output:
None
"""
@questionController.route('/submitQuestion',methods=['POST'])
def submitQuestion():
    title = request.get_json().get('title')
    content = request.get_json().get('content')
    fileUrl = request.get_json().get('fileUrl')
    tag = request.get_json().get('tag')

    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')

    decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    username = decoded_payload['username']

    question = Question(title,content,fileUrl,username,tag)
    db.session.add(question)
    db.session.commit()
    return success(message='问题创建成功')

"""
获取问题列表
input:
type 代表是要最新问题列表还是最热门问题列表
tag 要查询哪一种疾病
output:
问题列表
"""
@questionController.route('/getQuestionList',methods=['GET'])
def getQuestionList():
    # 根据type来返回结果 type==0代表最新问题 type==1代表最热问题
    needType = request.args.get('type')
    tag = request.args.get('tag')
    dataList = []
    if needType == str(0):
        if tag == None or len(tag) <= 0:
            # 按时间递减顺序查询
            questionList = Question.query.order_by(desc(Question.create_time)).all()
        else:
            # 按时间递减顺序查询 同时加入tag条件
            questionList = Question.query.filter(Question.tag.contains(tag)).order_by(desc(Question.create_time)).all()
    else:
        if tag == None or len(tag) <= 0:
            # 按访问量递减顺序查询
            questionList = Question.query.order_by(desc(Question.view)).all()
        else:
            questionList = Question.query.filter(Question.tag.contains(tag)).order_by(desc(Question.view)).all()
    
    for question in questionList:
        # 对于每一个问题 还要找到它的采纳的回答 最后一起构成造成一个对象存入dataList
        dataDict = question.to_dict()
        adoptionAnswer = Answer.query.filter_by(question_id=question.id).filter_by(adoption=1).first()
        if adoptionAnswer:
            # 找到之后 获取最佳回答者的信息
            adoptionUser = User.query.filter_by(username=adoptionAnswer.username).first()
            dataDict['username'] = adoptionUser.username
            dataDict['avatar'] = adoptionUser.avatar
            dataDict['hospital'] = adoptionUser.hospital
            dataDict['answer'] = adoptionAnswer.answer
            dataDict['answerCreateTime'] = adoptionAnswer.create_time
        dataList.append(dataDict)
    return success(message='获取问题列表成功',data=dataList)

"""
获取疾病热度排行榜
input:
None:
output:
疾病热度排行榜
"""
@questionController.route('/getDiseaseHotList',methods=['GET'])
def getDiseaseHotList():
    diseaseList = ['糖尿病视网膜病变','青光眼','白内障','AMD','高血压','近视','其他疾病/异常']
    dataList = []
    for disease in diseaseList:
        view_sum = Question.query.filter(Question.tag.contains(disease)).with_entities(func.sum(Question.view)).scalar()
        dictData = {
            'disease': disease,
            'hot': view_sum
        }
        dataList.append(dictData)

    return success(message='获取疾病热度排行榜成功',data=dataList)

"""
获取权威医生列表
input:
None:
output:
权威医生列表
"""
@questionController.route('/getPositiveDoctorList',methods=['GET'])
def getPositiveDoctorList():
    adoptionAnswerList = Answer.query.filter_by(adoption=1).all()
    dataDict = Counter()
    for answer in adoptionAnswerList:
        dataDict[answer.username] += 1
    counterList = list(dataDict.items())
    dataList = []
    for (username,count) in counterList:
        # 根据username查询出对应的用户信息
        user = User.query.filter_by(username=username).first()
        infoDict = {
            'avatar': user.avatar,
            'username': username,
            'hospital': user.hospital,
            'phone': user.phone,
            'adoptionCount': count
        }
        dataList.append(infoDict)
    return success(message='获取权威医生列表成功',data=dataList)

"""
点击问题 增加该问题的点击量
input:
问题id
output:
none
"""
@questionController.route('/clickQuestion',methods=['PUT'])
def clickQuestion():
    id = request.args.get('id')
    # 查询出对应的问题
    question = Question.query.filter_by(id=id).first()
    if question == None:
        return error(message='问题不存在')

    Question.query.filter_by(id=id).update({'view': question.view + 1})
    db.session.commit()
    return success(message='增加阅读量成功')

"""
提交一个问题的答案
input:
form
output:
none
"""
@questionController.route('/submitAnswer',methods=['POST'])
def submitAnswer():
    answer = request.get_json().get('answer')
    fileUrl = request.get_json().get('fileUrl')
    questionId = request.get_json().get('questionId')

    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')

    decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    username = decoded_payload['username']

    answer = Answer(username,answer,fileUrl,questionId)
    

    # 更新目标问题的回复数量
    question = Question.query.filter_by(id=questionId).first()
    if question == None:
        return error(message='问题不存在')

    Question.query.filter_by(id=questionId).update({'reply': question.reply + 1})

    db.session.add(answer)
    db.session.commit()

    return success(message='回复成功')

"""
获取一个问题的全部回答
input:
question id
output:
answer list
"""
@questionController.route('/getQuestionAllAnswer',methods=['GET'])
def getQuestionAllAnswer():
    questionId = request.args.get('questionId')
    answerList = Answer.query.filter_by(question_id=questionId).all()
    dataList = []
    for answer in answerList:
        # 对于每一个answer 还要知道会回复人信息
        user = User.query.filter_by(username=answer.username).first()
        dataDict = answer.to_dict()
        dataDict['avatar'] = user.avatar
        dataDict['username'] = user.username
        dataDict['hospital'] = user.hospital
        dataList.append(dataDict)

    return success(message='获取问题回复成功',data=dataList)

"""
将某个回答采纳为最佳答案
input:
answer id
output:
none
"""
@questionController.route('/adoptAnswer',methods=['PUT'])
def adoptAnswer():
    answerId = request.args.get('answerId')
    
    answer = Answer.query.filter_by(id=answerId).first()
    if answer == None:
        return error(message='回复不存在')
    
    Answer.query.filter_by(id=answerId).update({'adoption': 1})
    db.session.commit()

    return success(message='采纳成功')

"""
给医生私聊留言
input:
message form
output:
none
"""
@questionController.route('/leaveMessage',methods=['POST'])
def leaveMessage():
    content = request.get_json().get('content')
    fileUrl = request.get_json().get('fileUrl')
    toUsername = request.get_json().get('toUsername')

    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')

    decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    fromUsername = decoded_payload['username']

    message = Message(fromUsername,toUsername,fileUrl,content)
    db.session.add(message)
    db.session.commit()

    return success(message='留言发送成功')

"""
获取当前用户的留言信息
input:
username
output:
message list
"""
@questionController.route('/getUserMessage',methods=['GET'])
def getUserMessage():
    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')

    decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    username = decoded_payload['username']

    # 查询所以接收方是自己的留言
    messageList = Message.query.filter_by(to_username=username).filter_by(status=0).all()
    dataList = []
    for message in messageList:
        dataList.append(message.to_dict())
    return success(message='获取留言成功',data=dataList)

"""
回复留言 会新加一条留言到数据库
input:
message form
output:
none
"""
@questionController.route('/replyMessage',methods=['POST'])
def replyMessage():
    content = request.get_json().get('content')
    fileUrl = request.get_json().get('fileUrl')
    toUsername = request.get_json().get('toUsername')
    messageId = request.get_json().get('messageId')

    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')

    decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    fromUsername = decoded_payload['username']
    
    # 1.更新当前信息为已读
    Message.query.filter_by(id=messageId).update({'status': 1})

    # 2.插入回复留言
    message = Message(fromUsername,toUsername,fileUrl,content)
    db.session.add(message)
    db.session.commit()

    return success(message='留言发送成功')

"""
标记一条留言为已读留言
input:
message id
output:
none
"""
@questionController.route('/hasReadMessage',methods=['PUT'])
def hasReadMessage():
    messageId = request.args.get('messageId')

    Message.query.filter_by(id=messageId).update({'status': 1})
    db.session.commit()

    return success(message='标记已读成功')